/******************************************************************************
 * Copyright (C) 2014 ShenZhen YiHua Computer Co., Ltd.
 * All Rights Reserved.
 * 本软件为深圳怡化电脑股份有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体
 * 不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


/**
 * @Description 邮件工具类
 * @Author 杨文正
 * @Date 2014年10月28日 下午2:31:16
 */
public class MailTools
{
    private MimeMessage mimeMsg; // MIME邮件

    private Session session; // 邮件会话

    private Properties props; // 系统属性

    private String username = "pm_dev@yihuacomputer.com"; // smtp用户名和密码

    private String password = "Yhg14587";

    private Multipart mp; // Multipart附件,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage

    private String smtp = "smtp.yihuacomputer.com";
//    private String smtp = "172.18.0.18";

    /**
     * @param username 发送邮件的邮箱名称
     * @param password 发送邮件的邮箱密码
     */
    public MailTools(String username, String password)
    {
        this.username = username;
        this.password = password;
        setSmtpHost(smtp);
        createMimeMessage();
    }

    /**
     * @param hostName String
     */
    private void setSmtpHost(String hostName)
    {
        // System.out.println("设置系统属性：mail.smtp.host   =   "+hostName);
        if (props == null)
        {
            props = System.getProperties(); // 获得系统属性

        }
        props.put("mail.smtp.host", hostName); // 设置SMTP主机
        props.put("mail.smtp.auth", "true"); // 设置身份认证为false
    }

    /**
     * @return boolean
     */
    private boolean createMimeMessage()
    {
        try
        {
            session = Session.getDefaultInstance(props, null);
        }
        catch (Exception e)
        {
            return false;
        }
        try
        {
            mimeMsg = new MimeMessage(session); // 创建MIME邮件
            mp = new MimeMultipart();
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送邮件
     *
     * @param title 邮件标题
     * @param to 收件人,多邮箱以;做分割
     * @param content 内容
     * @return
     */
    public boolean sendMail(String title, String to, String content)
    {
        InternetAddress[] allmail = null;
        try
        {
            mimeMsg.setSubject(title, "GBK"); // 主题
            mimeMsg.setFrom(new InternetAddress(username)); // 发信人
            BodyPart bp = new MimeBodyPart();
//            bp.setContent(content, "text/html;charset=gb2312");
            bp.setContent(content, "text/html;charset=UTF-8");
            mp.addBodyPart(bp);

            String[] strto = ReturnSplit(to, ";");
            // toall = new InternetAddress[strto.length];

            try
            {
                allmail = new InternetAddress[strto.length];
                for (int i = 0; i < strto.length; i++)
                {
                    if (strto[i] == null)
                        continue;

                    if (!("".equals(strto[i])))
                        allmail[i] = new InternetAddress(strto[i]);
                }

            }
            catch (Exception ex)
            {

            }
            // message.setRecipients(Message.RecipientType.TO, toall);
            if (allmail != null)
                mimeMsg.setRecipients(Message.RecipientType.TO, allmail);

            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            return sendout();
        }
        catch (Exception e)
        {
            System.err.println("邮件设置失败!" + e);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送邮件
     *
     * @param title 邮件标题
     * @param to 收件人,多邮箱以;做分割
     * @param content 内容
     * @return
     */
    public boolean sendMail(String title, String to, String content, String bbc)
    {
        InternetAddress[] allmail = null;
        InternetAddress[] bbcmail = null;
        String[] strto = null;
        String[] strbbc = null;
        try
        {

            mimeMsg.setSubject(title, "GBK"); // 主题
            mimeMsg.setFrom(new InternetAddress(username)); // 发信人
            BodyPart bp = new MimeBodyPart();
//            bp.setContent(content, "text/html;charset=gb2312");
            bp.setContent(content, "text/html;charset=UTF-8");
            mp.addBodyPart(bp);

            if (!"".equals(to))
            {
                strto = ReturnSplit(to, ";");
                // toall = new InternetAddress[strto.length];

                try
                {
                    allmail = new InternetAddress[strto.length];
                    for (int i = 0; i < strto.length; i++)
                    {
                        if (strto[i] == null)
                            continue;

                        if (!("".equals(strto[i])))
                            allmail[i] = new InternetAddress(strto[i]);
                    }

                }
                catch (Exception ex)
                {

                }
            }

            if (!"".equals(bbc))
            {
                strbbc = ReturnSplit(bbc, ";");
                // toall = new InternetAddress[strto.length];

                try
                {
                    bbcmail = new InternetAddress[strbbc.length];
                    for (int i = 0; i < strbbc.length; i++)
                    {
                        if (strbbc[i] == null)
                            continue;

                        if ("null".equals(strbbc[i]))
                            continue;

                        if (!("".equals(strbbc[i])))
                            bbcmail[i] = new InternetAddress(strbbc[i]);
                    }

                }
                catch (Exception ex)
                {

                }
            }

            // message.setRecipients(Message.RecipientType.TO, toall);
            if (allmail != null)
                mimeMsg.setRecipients(Message.RecipientType.TO, allmail);

            if (bbcmail != null)
                mimeMsg.setRecipients(Message.RecipientType.BCC, bbcmail);

            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            sendout();
            return true;
        }
        catch (Exception e)
        {
            System.err.println("邮件设置失败!" + e);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送邮件
     *
     * @param title 邮件标题
     * @param to 收件人,多邮箱以;做分割
     * @param content 内容
     * @return
     */
    public boolean sendMailToCC(String title, String to, String content, String cc)
    {
        InternetAddress[] allmail = null;
        InternetAddress[] ccmail = null;
        String[] strto = null;
        String[] strcc = null;
        try
        {

            mimeMsg.setSubject(title, "GBK"); // 主题
            mimeMsg.setFrom(new InternetAddress(username)); // 发信人
            BodyPart bp = new MimeBodyPart();
//            bp.setContent(content, "text/html;charset=gb2312");
            bp.setContent(content, "text/html;charset=UTF-8");
            mp.addBodyPart(bp);

            if (!"".equals(to))
            {
                strto = ReturnSplit(to, ";");
                // toall = new InternetAddress[strto.length];

                try
                {
                    allmail = new InternetAddress[strto.length];
                    for (int i = 0; i < strto.length; i++)
                    {
                        if (strto[i] == null)
                            continue;

                        if (!("".equals(strto[i])))
                            allmail[i] = new InternetAddress(strto[i]);
                    }

                }
                catch (Exception ex)
                {

                }
            }

            if (!"".equals(cc))
            {
                strcc = ReturnSplit(cc, ";");
                // toall = new InternetAddress[strto.length];

                try
                {
                    ccmail = new InternetAddress[strcc.length];
                    for (int i = 0; i < strcc.length; i++)
                    {
                        if (strcc[i] == null)
                            continue;

                        if ("null".equals(strcc[i]))
                            continue;

                        if (!("".equals(strcc[i])))
                            ccmail[i] = new InternetAddress(strcc[i]);
                    }

                }
                catch (Exception ex)
                {

                }
            }

            // message.setRecipients(Message.RecipientType.TO, toall);
            if (allmail != null)
                mimeMsg.setRecipients(Message.RecipientType.TO, allmail);

            if (ccmail != null)
                mimeMsg.setRecipients(Message.RecipientType.CC, ccmail);
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            sendout();
            return true;
        }
        catch (Exception e)
        {
            System.err.println("邮件设置失败!" + e);
            e.printStackTrace();
            return false;
        }
    }

    private boolean sendout()
    {
        try
        {
            Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String) props.get("mail.smtp.host"), username, password);

            if (mimeMsg.getRecipients(Message.RecipientType.TO) != null)
                transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));

            if (mimeMsg.getRecipients(Message.RecipientType.BCC) != null)
                transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.BCC));
            
            if (mimeMsg.getRecipients(Message.RecipientType.CC) != null)
                transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));

            transport.close();
            return true;
        }
        catch (Exception e)
        {
            System.err.println("邮件发送失败！" + e);
            return false;
        }
    }

    /*
     * 分隔数据库的字段
     */
    public static String[] ReturnSplit(String strfield, String strsplit)
    {
        String[] mailAddress = null;

        if (strsplit.equals("|"))
        {
        	mailAddress = strfield.split("\\|");
        }
        else
        {
        	mailAddress = strfield.split(strsplit);
        }
        
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < mailAddress.length; i++) {
        	if (mailAddress[i].isEmpty() || mailAddress[i].equals("") || "null".equals(mailAddress[i]))
            {
                continue;
            }
        	list.add(mailAddress[i]);
		}
        mailAddress = (String[])list.toArray(new String[list.size()]);
        return mailAddress;
    }

    /**
     * @Title main 测试
     * @Description TODO(这里用一句话描述这个方法的作用)
     * @param args
     * @Returns void 返回类型
     */
    public static void main(String... args)
    {
        String content = "<table border='1'><tr><td>发送一个表格</td></tr><tr><td>发送一个表格</td></tr><tr><td>发送一个表格</td></tr><tr><td>发送一个表格</td></tr></table>";

        MailTools mail = new MailTools("From_tech@yihuacomputer.com", "Dyh21543");

        mail.sendMail("标题", "hufangyou@yihuacomputer.com;", content,
                "huangzhiyong-sz@yihuacomputer.com;chengdong@yihuacomputer.com;xiequanwu@yihuacomputer.com;");

        System.out.println("发送成功");
    }
}
